package com.jrx.anytxn.param.job.bactchBillCompare.config;

import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import com.jrx.anytxn.param.config.BillCompareConfig;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransCompareDetail;
import com.jrx.anytxn.param.entity.TlThirdBillDetail;
import com.jrx.anytxn.param.job.bactchBillCompare.step.BillDetailUnmatchedWriter;
import com.jrx.anytxn.param.job.bactchBillCompare.step.ThirdDetailUnmatchedListener;
import com.jrx.anytxn.param.job.bactchBillCompare.step.ThirdDetailUnmatchedProcessor;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 核心对账-将未能匹配到txn交易记录的账务明细写入对账明细表job
 *
 * @author : zcc
 * 2020/11/26
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class BatchThirdDetailUnmatchedConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(BatchThirdDetailUnmatchedConfiguration.class);

    @Resource(name = "paramSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    private ThirdDetailUnmatchedProcessor thirdDetailUnmatchedProcessor;
    @Autowired
    private BillDetailUnmatchedWriter billDetailUnmatchedWriter;
    @Autowired
    private ThirdDetailUnmatchedListener thirdDetailUnmatchedListener;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private BillCompareConfig billCompareConfig;

    @Bean
    public Job thirdDetailUnmatchedJob() throws IOException {
        return jobBuilderFactory.get("thirdDetailUnmatchedJob").incrementer(new RunIdIncrementer()).listener(thirdDetailUnmatchedListener)
                .start(thirdDetailUnmatchedStep()) //将未能匹配到txn交易记录的账务明细写入对账明细表
                .build();
    }

    @Bean
    public Step thirdDetailUnmatchedStep(){
        return stepBuilderFactory.get("thirdDetailUnmatchedStep")
                .<TlThirdBillDetail, TlBillTransCompareDetail>chunk(anytxnBatchProperties.getBatchBillCompareConfiguration().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(remainDetailUnmatchedReader())
                .processor(thirdDetailUnmatchedProcessor)
                .writer(billDetailUnmatchedWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getBatchBillCompareConfiguration().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<TlThirdBillDetail> remainDetailUnmatchedReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.XIB_ORG_NUMBER);
        // 设置指定对账日期
        Date today = billCompareConfig.getToday();
        if (Objects.nonNull(today)) {
            org.setToday(today);
        }
        MyBatisCursorItemReader<TlThirdBillDetail> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.param.mapper.ext.ExtTlThirdBillDetailMapper.selectByTenIdAndBusDateAndComFlag");
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", org.getTenantId());
        map.put("businessDate", org.getToday());
        map.put("compareFlag", Constant.COMPARE_FLAG_0);
        map.put("thirdChannel", billCompareConfig.getThirdChannel());
        cursorItemReader.setParameterValues(map);

        SynchronizedItemStreamReader<TlThirdBillDetail> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

}